<?php

declare(strict_types=1);

namespace App\Controller\AdminApi;

use Dotenv\Validator;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\DeleteMapping;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;
use App\Exception\XZXValidationException;
use App\Service\SysAdminService;
use App\Utils\CustomUtils;
use App\Utils\DateUtils;
use Psr\Container\ContainerInterface;
use Hyperf\Logger\LoggerFactory;
use App\Middleware\AdminApi\AdminJWTAuthMiddleware;

/**
 * Class SysAdminController
 * @package App\Controller
 *
 * @Controller(prefix="/admin/api/sysAdmin")
 */
class SysAdminController extends AdminBaseController
{
    /**
     * @Inject()
     * @var ValidatorFactoryInterface
     */
    protected $validationFactory;

    /**
     * @Inject()
     * @var SysAdminService
     */
    protected $SysAdminService;

    /**
     * @var \Psr\Log\LoggerInterface
     */
    protected $logger;

    public function __construct(LoggerFactory $loggerFactory)
    {
        // 第一个参数对应日志的 name, 第二个参数对应 config/autoload/logger.php 内的 key
        $this->logger = $loggerFactory->get('log', 'default');
    }

    /**
     * 查看
     * @PostMapping(path = "get")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function get(RequestInterface $request)
    {
        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'id' => 'required|uuid',
            ]
        );

        if ($validator->fails()){
            // Handle exception
            $errorMessage = $validator->errors()->first();  
            throw new XZXValidationException($errorMessage);
        }

        $param = $request->all();
        return $this->SysAdminService->get($param);
    }

    /**
     * 编辑
     * @PostMapping(path = "edit")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function edit(RequestInterface $request)
    {

        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'id'                    => 'required|uuid',
                // 'username'           => 'sometimes|required|between:4,8|alpha_num',
                'password'              => 'sometimes|required|between:5,16|alpha_dash|confirmed',
                'password_confirmation' => 'sometimes|required|between:5,16|alpha_dash',
                'nick'                  => 'sometimes|required',
                'realName'              => 'sometimes|required',
                'mobile'                => 'sometimes|required',
                'email'                 => 'sometimes|required|email',
                'roleId'                => 'sometimes|required|uuid',
                'status'                => 'sometimes|required|integer|max:1|min:0',
                'googleAuthSecret'      => 'sometimes|size:16',
                'mchIdList'             => 'sometimes|array',                
            ]
        );

        if ($validator->fails()){
            // Handle exception
            $errorMessage = $validator->errors()->first();  
            throw new XZXValidationException($errorMessage);
        }

        $param = $request->all();
        $ext = $this->request->getAttribute("ext");
        $param['uid']      =  $ext['uid'];         
        $param['createBy']      =  $ext['createBy']; 
        return $this->SysAdminService->edit($param);
    }

    /**
     * 添加
     * @PostMapping(path = "add")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function add(RequestInterface $request)
    {

        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'username'              => 'required|between:4,8|alpha_num',
                'password'              => 'required|between:5,16|alpha_dash|confirmed',
                'password_confirmation' => 'required|between:5,16|alpha_dash',
                'realName'              => 'required',
                'mobile'                => 'required',
                'email'                 => 'required|email',
                'roleId'                => 'required|uuid',
                'status'                => 'required|integer|max:1|min:0',
                'mchIdList'             => 'sometimes|array',
            ]
        );        
        
        if ($validator->fails()){
            // Handle exception
            $errorMessage = $validator->errors()->first();  
            throw new XZXValidationException($errorMessage);
        }

        $param = $request->all();
        $ext = $this->request->getAttribute("ext");
        $param['uid']      =  $ext['uid'];         
        $param['createBy']      =  $ext['createBy']; 
        CustomUtils::xzxDebug($param);
        return $this->SysAdminService->add($param);
    }

    /**
     * 删除
     * @PostMapping(path = "del")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function del(RequestInterface $request)
    {

        // $validator = $this->validationFactory->make(
        //     $request->all(),
        //     [
        //         'id' => 'required|uuid',
        //     ],
        // );

        // if ($validator->fails()){
        //     // Handle exception
        //     $errorMessage = $validator->errors()->first();  
        //     throw new XZXValidationException($errorMessage);
        // }

        // $param = $request->all();
        // return $this->SysAdminService->del($param);
    }

    /**
     * 查询
     * @PostMapping(path = "list")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function list(RequestInterface $request)
    {

        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'page'            => 'required|integer|min:1',
                'limit'           => 'required|integer|min:1',
                'search.email'    => 'sometimes|email',
                'search.roleId'   => 'sometimes|uuid',
                'search.status'   => 'sometimes|integer|max:1|min:0',                
                'search.username' => 'sometimes|between:4,8|alpha_num',
            ]
        );

        if ($validator->fails()){
            // Handle exception
            $errorMessage = $validator->errors()->first();  
            throw new XZXValidationException($errorMessage);
        }
        $param = $request->all();
        // CustomUtils::xzxDebug($request);
        $ext = $this->request->getAttribute("ext");
        $param['uid']      =  $ext['uid']; 
        // CustomUtils::xzxDebug($param);
        if(isset($param['search'])){
            $search = $param['search'];
            CustomUtils::xzxAddSearch($param, $search, 'username');
            CustomUtils::xzxAddSearch($param, $search, 'email');
            CustomUtils::xzxAddSearch($param, $search, 'status');
            CustomUtils::xzxAddSearch($param, $search, 'roleId');
            CustomUtils::xzxAddSearch($param, $search, 'createTimeRange');
            CustomUtils::xzxAddSearch($param, $search, 'extraType');
            if(isset($param["createTimeRange"]))
            {
                try {
                    $param['createTimeRange'][0] = DateUtils::dateToTimeStamp($param['createTimeRange'][0]);
                    $param['createTimeRange'][1] = DateUtils::dateToTimeStamp($param['createTimeRange'][1]);
                } catch (\Throwable $th) {
                    unset($param['createTimeRange']);
                }
            }
        }
        

        
        return $this->SysAdminService->list($param);
    }

    /**
     * options
     * @PostMapping(path = "getStatusOptions")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */    
    public function getStatusOptions (RequestInterface $request) {
        return $this->SysAdminService->getStatusOptions();
    }

    /**
     * 重置google密钥
     * @PostMapping(path = "resetGoogleAuthSecret")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */ 
    public function resetGoogleAuthSecret(RequestInterface $request) {

        // $param['id'] = trim($request->post('id'));
        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'id' => 'required|uuid',
            ]
        );

        if ($validator->fails()){
            // Handle exception
            $errorMessage = $validator->errors()->first();  
            throw new XZXValidationException($errorMessage);
        }

        $param = $request->all();

        return $this->SysAdminService->resetGoogleAuthSecret($param);
    }

    /**
     * Login
     * @PostMapping(path = "login")
     */    
    public function login(RequestInterface $request) {
              
        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'username' => 'required|between:4,8|alpha_num',
                'password' => 'required|between:5,16|alpha_dash',
                'code' => 'required',
            ]
        );

        if ($validator->fails()){
            // Handle exception
            $errorMessage = $validator->errors()->first();  
            throw new XZXValidationException($errorMessage);
        }
        $param = $request->all();
        return $this->SysAdminService->login($param);
    }

    /**
     * Login
     * @PostMapping(path = "getmenulist")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */ 
    public function getMenuList(RequestInterface $request) {
        
        
        $param = array();
        // CustomUtils::xzxDebug($request);
        $ext = $this->request->getAttribute("ext");
        $param['uid']      =  $ext['uid']; 
               
        CustomUtils::xzxDebug($param);
        return $this->SysAdminService->menuList($param['uid']);
        // return xeResponseData($result['code'],$result['message'],$result['data']);
    }

    /**
     * Login
     * @PostMapping(path = "logout")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function logout(RequestInterface $request) {
        
        $param = array();
        $ext = $this->request->getAttribute("ext");
        $param['uid']      =  $ext['uid']; 
        
        CustomUtils::xzxDebug($param);
        
        return $this->SysAdminService->logout($param);
    }

    /**
     * option
     * @PostMapping(path = "option")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function option(RequestInterface $request) {
        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'extraType' => 'sometimes|integer|max:3|min:0', // 0.忽略 1.销售 2.代理商 3.销售总监
                'level'     => 'sometimes|integer', // 1.销售一级 2.销售二级
            ]
        );

        if ($validator->fails()){
            // Handle exception
            $errorMessage = $validator->errors()->first();  
            throw new XZXValidationException($errorMessage);
        }        
        $param = $request->all();
        $ext = $this->request->getAttribute("ext");
        $param['uid'] =  $ext['uid'];

        return $this->SysAdminService->getOption($param);
    }

}